package bookhive.catalog;

import java.io.IOException;
import java.util.Enumeration;

import net.jxta.document.Element;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.XMLDocument;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;

public class RedunderResponseHandler implements PipeMsgListener {

	RedunderPeer rpeer = null;

	public RedunderResponseHandler(RedunderPeer peer) {
		rpeer = peer;
	}

	public void pipeMsgEvent(PipeMsgEvent event) {

		Message msg = event.getMessage();
		MessageElement response = msg.getMessageElement("Response");
		try {
			XMLDocument responseDocument = (XMLDocument) StructuredDocumentFactory
					.newStructuredDocument(response);

			String catalogPidString = (String) ((Element) responseDocument
					.getChildren("CatalogPeerID").nextElement()).getValue();
			if (catalogPidString.equals(rpeer.getPeerID().toString()))
				return;

			Enumeration resultElementEnum = responseDocument
					.getChildren("Result");
			while (resultElementEnum.hasMoreElements()) {
				Element resultEl = (Element) resultElementEnum.nextElement();

				String queryData = ((Element) resultEl.getChildren("QueryData")
						.nextElement()).getValue().toString();
				String queryType = ((Element) resultEl.getChildren("QueryType")
						.nextElement()).getValue().toString();
				if (queryType.equals("data")) {
					Enumeration recordsEnum = ((Element) resultEl.getChildren(
							"Records").nextElement()).getChildren("Record");
					if (recordsEnum.hasMoreElements()) {
						rpeer.addSource(queryData, catalogPidString);
					}
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

	}

}
